package com.bizzard.product.service.impl;

import com.bizzard.basic.exception.BusinessException;
import com.bizzard.basic.service.IBaiduAiAuditService;
import com.bizzard.product.domain.Product;
import com.bizzard.product.domain.ProductDetail;
import com.bizzard.product.mapper.ProductDetailMapper;
import com.bizzard.product.mapper.ProductMapper;
import com.bizzard.product.service.IProductService;
import com.bizzard.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {
    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Transactional
    @Override
    public void add(Product product) {
        super.add(product);
        ProductDetail productDetail = product.getDetail();
        if (productDetail != null) {
            productDetail.setProductId(product.getId());
            productDetailMapper.save(productDetail);
        }
    }

    @Override
    public void update(Product product) {
        super.update(product);
        ProductDetail productDetail = product.getDetail();
        if (productDetail != null) {
            productDetail.setProductId(product.getId());
            productDetailMapper.updateDetailByProductId(productDetail);
        }
    }

    @Transactional
    @Override
    public void del(Long id) {
        super.del(id);
        productDetailMapper.delDetailByProductId(id);
    }

    /**
     * 服务上架
     * @param ids
     * @param request 接收当前登录人信息，用来修改服务上下架日志表数据
     */
    @Override
    public void onsale(Long[] ids, HttpServletRequest request) {

        for (Long id : ids) {
            Product product = productMapper.loadById(id);
            // 1.上架之前对文本和图片做审核
            Boolean textBoo = baiduAiAuditService.textAudit(product.getName());
            Boolean imageBoo = baiduAiAuditService.imageAudit(product.getResources());
            if (textBoo && imageBoo) {
                // 2.审核通过：修改状态 + 添加上架的审核成功日志
                product.setOnsaletime(new Date());
                product.setState(1L);
                product.setOffsaletime(null);
                productMapper.update(product);

            } else {
                throw new BusinessException("审核失败！！！内容有非法数据");
            }
        }
    }


    /**
     * 服务下架
     * @param ids
     */
    @Override
    public void offsale(Long[] ids) {
        Date offsaletime = new Date();
        productMapper.offsale(ids, offsaletime);
    }



}
